package pers.vinsonws.jianghu.serverspring.handers;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import pers.vinsonws.jianghu.codeCompont.MsgEveryPro;
import pers.vinsonws.jianghu.serverspring.controller.ApplyChatRoomCtrl;
import pers.vinsonws.jianghu.serverspring.controller.ChatCtrl;
import pers.vinsonws.jianghu.serverspring.controller.InitClientCtrl;
import pers.vinsonws.jianghu.serverspring.controller.SignCtrl;
import pers.vinsonws.jianghu.serverspring.entity.ApplyChatRooms;
import pers.vinsonws.jianghu.serverspring.session.NetSession;
import pers.vinsonws.jianghu.serverspring.session.SessionManager;
import pers.vinsonws.jianghu.tools.MergeMessage;
import pers.vinsonws.jianghu.util.ChatRoom;
import pers.vinsonws.jianghu.util.User;

import java.util.ArrayList;
import java.util.List;

/**
 * @auther vinsonws
 * @date 2018/11/7 22:03
 * 异常抛到这儿
 */
@Component
public class ServerMainReadProcess {
    private static final Logger log = LoggerFactory.getLogger(ServerMainReadProcess.class);
    @Autowired
    private ApplyChatRoomCtrl applyChatRoomCtrl;

    @Autowired
    private ChatCtrl chatCtrl;

    @Autowired
    private InitClientCtrl initClientCtrl;

    @Autowired
    private SignCtrl signCtrl;

    public void readProcess(MsgEveryPro.Message message, ChannelHandlerContext ctx){
        MsgEveryPro.Message message1 = null;
        List<MsgEveryPro.Message> messages = null;
        NetSession session = SessionManager.getSession(ctx.channel());
        User sendUser = session.getUser();
        String logger = null;
        if ((message.getType() != 1 && message.getType() != 2) && !session.isOnline()) {
            logger = "未登录无效动作";
        } else {
            switch (message.getType()){
                case 0: messages = initClient(message, sendUser.getId());
                logger = "初始化客户端";
                break;
                case 1: message1 = registerUser(message);
                logger = "注册";
                break;
                case 2: message1 = loginUser(message, ctx.channel(), session);
                logger = "登录";
                break;
                case 3: message1 = applyRoom(message);
                logger = "申请聊天室";
                break;
                case 4: message1 = dealApply(message);
                logger = "处理申请";
                break;
                case 5: message1 = alterInfo(message, session);
                logger = "更改资料";
                break;
                case 6: loginOut(sendUser.getId());
                logger = "登出";
                break;
                case 7: chatOneToOne(message);
                logger = "聊天-一对一";
                break;
                case 8: chatRoom(message);
                logger = "聊天-聊天室";
                break;
                case 9: messages = userLookApplyHerself(message);
                logger = "用户查看申请";
                break;
                case 10: messages = adminLookApplyHerself(message);
                logger = "管理员查看申请";
                break;
                case 11:adminOperateApply(message);
                logger = "管理员操作申请";
                break;
                case 12: messages = onlineUsers(message);
                default: //暂时不做处理
                    logger = "无效处理类型";
                    break;
            }
        }
        log.info(ctx.channel().remoteAddress().toString() + "进行" + logger + "成功");
        if (message1 != null) ctx.channel().writeAndFlush(message1);
        if (messages != null) {
            for (MsgEveryPro.Message message2:messages){
                ctx.channel().writeAndFlush(message2);
            }
        }
    }

    /** 12
     *
     * @param message
     * @return
     */
    private List<MsgEveryPro.Message> onlineUsers(MsgEveryPro.Message message) {
        List<MsgEveryPro.Message> messages = new ArrayList<>();
        for (User user:initClientCtrl.getAllOnlineUsers()){
            MsgEveryPro.Message.Builder messageSend = MsgEveryPro.Message.newBuilder();
            String messageStr;
            messageSend.setDateLong(System.currentTimeMillis());
            messageSend.setOnline(true);
            messageSend.setType(message.getType());
            String[] messageArray = {String.valueOf(user.getId()), user.getUserName()};
            messageStr = MergeMessage.infoToMessage(messageArray,message.getType());
            messageSend.setMessage(messageStr);
            messages.add(messageSend.build());
        }
        return messages;
    }


    /** 0
     * 这里是发送聊天室的 所以message只用设置date,message,online,type
     * @param message
     * @param userId
     * @return
     */
    private List<MsgEveryPro.Message> initClient(MsgEveryPro.Message message, int userId){
        List<MsgEveryPro.Message> messages = new ArrayList<>();
        for (ChatRoom chatRoom1:initClientCtrl.getAllChatRoom()){
            MsgEveryPro.Message.Builder messageSend = MsgEveryPro.Message.newBuilder();
            String messageStr;
            int belongToMe = 0;//不属于
            int isMaster = 0;
            messageSend.setDateLong(System.currentTimeMillis());
            messageSend.setOnline(true);
            messageSend.setType(message.getType());
            for (ChatRoom chatRoom2:initClientCtrl.getJoinedChatRoom(userId)){
                if (chatRoom1.getId() == chatRoom2.getId()){
                    belongToMe = 1;//属于
                }
            }
            if (chatRoom1.getMaster().getId() == message.getUserSendId()) isMaster =1;
            String[] messageArray = {String.valueOf(chatRoom1.getId()), chatRoom1.getName(),
                    String.valueOf(belongToMe), String.valueOf(isMaster)};
            messageStr = MergeMessage.infoToMessage(messageArray,message.getType());
            messageSend.setMessage(messageStr);
            messages.add(messageSend.build());
        }
        return messages;
    }

    /** 1
     * 注册
     * @param message
     * @return
     */
    private MsgEveryPro.Message registerUser(MsgEveryPro.Message message){
        MsgEveryPro.Message.Builder message1 = MsgEveryPro.Message.newBuilder();
        message1.setDateLong(System.currentTimeMillis());
        message1.setType(message.getType());
        try {
            message1.setMessage(signCtrl.toSignUp(message));
        } catch (Exception e) {
            log.info("用户注册失败");
            message1.setMessage(":22login22:0");
        }
        return message1.build();
    }

    /** 2
     * 登录
     * @param message
     * @param channel
     * @param session
     * @return
     */
    private MsgEveryPro.Message loginUser(MsgEveryPro.Message message, Channel channel, NetSession session){

        return signCtrl.toSignIn(message, channel, session);
    }

    /** 3
     * 提交申请
     * @param message
     * @return
     */
    private MsgEveryPro.Message applyRoom(MsgEveryPro.Message message){
        MsgEveryPro.Message.Builder message1 = MsgEveryPro.Message.newBuilder();
        message1.setDateLong(System.currentTimeMillis());
        message1.setType(message.getType());
        message1.setOnline(true);
        applyChatRoomCtrl.recordApplyRrquest(message);
        return message1.build();
    }

    /** 4
     * 管理员处理申请
     * @param message
     * @return
     */
    private MsgEveryPro.Message dealApply(MsgEveryPro.Message message){
        MsgEveryPro.Message.Builder message1 = MsgEveryPro.Message.newBuilder();
        message1.setDateLong(System.currentTimeMillis());
        message1.setType(message.getType());
        message1.setOnline(true);
        if (applyChatRoomCtrl.operateApplyInfo(message)){
            String[] ss= {"1"};
            message1.setMessage(MergeMessage.infoToMessage(ss, message.getType()));
        }
        return message1.build();
    }

    /** 5
     * 修改个人信息 5
     * @param message
     * @param session
     * @return
     */
    private MsgEveryPro.Message alterInfo(MsgEveryPro.Message message, NetSession session){
        MsgEveryPro.Message.Builder message1 = MsgEveryPro.Message.newBuilder();
        message1.setDateLong(System.currentTimeMillis());
        message1.setType(message.getType());
        message1.setOnline(true);
        message1.setMessage(signCtrl.updateUserInfo(message, session));
        return message1.build();
    }

    /** 6
     * 退出 6
     * 暂无
     */
    private void loginOut(int id){
        signCtrl.loginOut(id);
    }

    /** 7
     * 发送私人聊天，直接在这里面发送消息不返回值
     * @param message
     */
    private void chatOneToOne(MsgEveryPro.Message message){
        chatCtrl.dealChatOneMessage(message);
    }

    /** 8
     * 发送聊天室消息
     * @param message
     */
    private void chatRoom(MsgEveryPro.Message message){
        chatCtrl.dealChatRoomMessage(message);
    }

    /**  9
     * 用户查看申请
     * @param message
     * @return
     */
    private List<MsgEveryPro.Message> userLookApplyHerself(MsgEveryPro.Message message){
        List<MsgEveryPro.Message> messages = new ArrayList<>();
        for (ApplyChatRooms applyChatRooms:
                applyChatRoomCtrl.userGetApplyRecord(message)) {
            messages.add(applyInfoToMessage(message, applyChatRooms));
        }
        return messages;
    }

    /** 10
     * 管理员查看申请
     * @param message
     * @return
     */
    private List<MsgEveryPro.Message> adminLookApplyHerself(MsgEveryPro.Message message){
        List<MsgEveryPro.Message> messages = new ArrayList<>();
        for (ApplyChatRooms applyChatRooms:
                applyChatRoomCtrl.adminGetApplyRecord(message)) {
            if (applyInfoToMessage(message, applyChatRooms) != null)
                messages.add(applyInfoToMessage(message, applyChatRooms));
        }
        return messages;
    }

    /**
     * 上两个方法的工具
     * @param message
     * @param applyChatRooms
     * @return
     */
    private MsgEveryPro.Message applyInfoToMessage(MsgEveryPro.Message message, ApplyChatRooms applyChatRooms){
        MsgEveryPro.Message.Builder messageSend = MsgEveryPro.Message.newBuilder();

        String messageStr;
        messageSend.setDateLong(System.currentTimeMillis());
        messageSend.setOnline(true);
        messageSend.setType(message.getType());
        messageSend.setChatRoomOrUserRecvId(message.getChatRoomOrUserRecvId());
        if (applyChatRooms.isStatus()) return null;
        String[] messageArray = {String.valueOf(applyChatRooms.getUserId())};
        messageStr = MergeMessage.infoToMessage(messageArray, message.getType());
        messageSend.setMessage(messageStr);
        return messageSend.build();
    }

    /** 11
     * 管理员操作申请
     * @param message
     * @return
     */
    private void adminOperateApply(MsgEveryPro.Message message){
        if (applyChatRoomCtrl.operateApplyInfo(message)){
            log.info("管理员操作用户成功");
        } else {
            log.info("管理员操作用户失败");
        }
    }
}
